package com.woniuxy.project115.kaer.gateway.exception;

import cn.hutool.json.JSONUtil;
import com.woniuxy.project115.kaer.commons.util.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author HuH
 * @version 1.0
 * @CreatTime 2025-01-04 15:38
 * @description
 */
@Component
public class GatewayGlobalExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable throwable) {
        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
            System.out.println(throwable.getMessage());
            Result<Object> result = new Result<>(500, throwable.getMessage(), null, null);
            String jsonStr = JSONUtil.toJsonStr(result);
            return exchange.getResponse().bufferFactory().wrap(jsonStr.getBytes());
        }));

    }
}
